<template>
  <div class="app-container">
    <el-form ref="elForm" :disabled="$route.query.isInfo || isInfo" :model="formData" :rules="rules" size="medium"
      label-width="120px">
      <h2 style="text-align: center">内部质量监控</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="年度" prop="year">
            <el-date-picker format="yyyy" value-format="yyyy" v-model="formData.year" type="year" placeholder="选择年">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <h4 class="form-header h4">
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <!-- <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button> -->
      </h4>
      <el-table :data="formData.contentList" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column min-width="200" label="比对项目参数" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.dbxmjcs`" :rules="rules.dbxmjcs">
              <el-input :disabled="$route.query.isEdit" v-model="scope.row.dbxmjcs" placeholder="请输入比对项目参数"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="部门" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.cbbmdwId`" :rules="rules.cbbmdwId">
              <el-cascader :disabled="$route.query.isEdit" ref="references" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                v-model="scope.row.cbbmdwId" :options="deptOptions" @change="changeCascaderNums"
                @visible-change="visibleChange($event, scope.$index)"></el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="监控人员" width="200" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.userId`" :rules="rules.userId">
              <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeOpen($event, scope.$index)"
                placeholder="请选择监控人员" v-model="scope.row.userId"></UserDialogSelection>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="能力验证的方式" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.nlyzfs`" :rules="rules.nlyzfs">
              <el-select :disabled="$route.query.isEdit" v-model="scope.row.nlyzfs" filterable placeholder="请选择能力验证的方式">
                <el-option v-for="dict in dict.type.sys_in_verification_type" :key="dict.value" :label="dict.label"
                  :value="dict.label" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="250" label="计划时间" prop="price" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.ksjhsj`" :rules="rules.ksjhsj">
              <el-date-picker :disabled="$route.query.isEdit" v-model="scope.row.optenTime" type="daterange"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" @change="changeDaterange($event, scope.$index)">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="250" label="计划时间" prop="price" align="center">
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="handleDele(scope.$index)">删行</el-button>
          </template>
        </el-table-column>
        <template v-if="formData.status === 'end'">
          <el-table-column min-width="200" label="完成情况" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`contentList.${scope.$index}.wcqk`" :rules="rules.wcqk">
                <el-input v-model="scope.row.wcqk" placeholder="请输入完成情况"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="备注" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`contentList.${scope.$index}.remark`" :rules="rules.remark">
                <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column min-width="500" label="附件" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`contentList.${scope.$index}.file`" :rules="rules.file">
                <FileUpload v-model="scope.row.file"></FileUpload>
              </el-form-item>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(1)">提交</el-button>
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(0)">暂存</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import {
  monitorEait,
  monitorAdd,
  detailMonitor,
} from "@/api/monitor/inOutMonitor.js";
import { deptTreeSelect } from "@/api/system/user.js";
import {
  cultivateYearPlanAdd,
  updategcultivateYearPlan,
  cultivateYearPlanInfo,
} from "@/api/cultivate/yearPlan.js";
import { getDicts } from "@/api/system/dict/data.js";
export default {
  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
  },
  components: {},
  dicts: ["sys_in_verification_type"],
  data() {
    return {
      userIdList: [],
      formData: {
        year: null,
        contentList: [
          {
            optenTime: null,
            qualityMonitorId: undefined,
            cbbmdwId: "",
            joinUserList: [],
            cbbmdw: undefined,
            terrainType: undefined,
            ksjhsj: null,
            jsjhsj: null,
            content: undefined,
            hostUserName: undefined,
            remark: undefined,
            result: undefined,
            file: undefined,
            // userids: [],
            userId: undefined,
            username: undefined,
          },
        ],
      },
      deptOptions: [],
      rules: {
        dbxmjcs: [
          {
            required: true,
            message: "比对项目参数",
            trigger: "blur",
          },
        ],
        file: [
          {
            required: false,
            message: "请上传附件",
            trigger: "change",
          },
        ],
        year: [
          {
            required: true,
            message: "请选择年",
            trigger: "change",
          },
        ],
        // content: [
        //   {
        //     required: true,
        //     message: "请输入培训内容",
        //     trigger: "blur",
        //   },
        // ],
        nlyzfs: [
          {
            required: true,
            message: "请输入能力验证方式",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: false,
            message: "请输入备注",
            trigger: "blur",
          },
        ],
        wcqk: [
          {
            required: false,
            message: "请输入完成情况",
            trigger: "blur",
          },
        ],
        ksjhsj: [
          {
            required: true,
            message: "请选择计划时间",
            trigger: "change",
          },
        ],
        cbbmdwId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
      },
      deptTreeSelect: [],
      showGroup: false
    };
  },
  computed: {},
  created() {

    this.getDeptTree();
  },
  mounted() { },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        if (this.$route.query.isEdit || this.$route.query.isEdit1 || this.$route.query.isInfo || this.isInfo) {
          this.getinfo();
        }
      });
    },
    chanageUser(e, i) {
      this.formData.contentList[i].joinUserList = e.map((i) => {
        return {
          userId: i.userId,
          userName: i.userName,
        };
      });
    },
    changeDaterange(e, i) {
      console.log(e, i);
      this.formData.contentList[i].ksjhsj = e[0];
      this.formData.contentList[i].jsjhsj = e[1];
    },
    changeOpen(e, i) {
      console.log(e, i);
      let idList = []
      let nameList = []
      e.forEach((i) => {
        idList.push(i.userId)
        nameList.push(i.nickName)
      });
      console.log(idList.toString(), 'idList');
      this.formData.contentList[i].username = nameList.toString()
      this.formData.contentList[i].userId = idList.toString()
      console.log(this.formData.contentList[i].userId);
      console.log(this.formData.contentList[i]);
    },
    changeCascaderNums(e, i) {
      console.log(e, i);
      this.showGroup = e.length > 0 ? true : false
    },
    visibleChange(e, i) {
      console.log(e);
      if (!e && this.showGroup) {
        let arr = this.$refs.references.getCheckedNodes()
        let list = []
        let label = []
        arr.forEach((item, index) => {
          list.push(item.value)
          label.push(item.label)
        })
        console.log(list);
        this.formData.contentList[i].deptIdReplace = list.toString()
        this.formData.contentList[i].deptNameReplace = label.toString()
        // console.log(this.formData.userList1[i].deptName, 'this.formData.userList1[i].deptId');
      }
    },
    handleAdd() {
      this.formData.contentList.push({
        qualityMonitorId: undefined,
        optenTime: null,
        cbbmdwId: "",
        joinUserList: [],
        cbbmdw: undefined,
        terrainType: undefined,
        ksjhsj: null,
        jsjhsj: null,
        content: undefined,
        hostUserName: undefined,
        remark: undefined,
        result: undefined,
        file: undefined,
        userId: undefined,
        username: undefined,
      });
    },
    handleDele(e) {
      if (this.formData.contentList.length == 1) return;
      this.formData.contentList.splice(e, 1);
    },
    getinfo() {
      return detailMonitor(this.$route.query.id || this.id).then((response) => {
        this.formData = response.data;
        // this.formData.contentList.forEach((i) => {
        //   this.$set(
        //     i,
        //     "userids",
        //     i.joinUserList.map((e) => e.userId)
        //   );
        // });
        this.formData.contentList.forEach((item, i) => {
          let timeArr = [];
          timeArr.push(this.formData.contentList[i].ksjhsj);
          timeArr.push(this.formData.contentList[i].jsjhsj);
          this.formData.contentList[i].optenTime = timeArr;
          // this.formData.contentList[i].cbbmdwId = Number(
          //   this.formData.contentList[i].cbbmdwId
          // );
          let list1 = []
          item.cbbmdwId = item.cbbmdwId.split(',')
          item.cbbmdwId = item.cbbmdwId.map(i => parseInt(i))
          console.log(item.cbbmdwId, 'item.cbbmdwId');
          item.cbbmdw = item.cbbmdw.split(',')
          item.cbbmdwId.map(i => {
            list1.push(this.findParentLot(i))
          })
          item.cbbmdwId = list1
        });
      });
    },
    // 创建新数组 返回
    findParentLot(id) {
      const arr = []
      this.deployIdFun(this.deptOptions, id, arr)
      return arr.reverse()
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      // console.log(options);
      options.forEach((v) => {
        if (v.id === id) {
          newArr.push(id)
          // console.log(newArr, 'newArr');
          if (!v.parentId || v.parentId !== '0') {
            this.deployIdFun(this.deptOptions, v.parentId, newArr)
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr)
          }
        }
      })
    },
    submitForm(item) {
      let query = JSON.parse(JSON.stringify(this.formData));
      query.status = item == 0 ? 'draft' : 'audit'
      query.type = 1;
      if (item == 0) {
        if (!query.year) {
          this.$message.error('请选择年份');
          return;
        }
        if (query.contentList.length > 0) {
          query.contentList.forEach((e, i) => {
            e.cbbmdwId = e.deptIdReplace
            e.cbbmdw = e.deptNameReplace
            e.userId = e.userId ? e.userId.toString() : e.userId

          });
        }
        if (this.formData.qualityMonitorId != undefined) {
          monitorEait(query).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.resetForm();
          });
        } else {
          monitorAdd(query).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.resetForm();
          });
        }
      }
      this.$refs["elForm"].validate((valid) => {
        if (valid) {

          query.contentList.forEach((e, i) => {
            e.cbbmdwId = e.deptIdReplace
            e.cbbmdw = e.deptNameReplace
            e.userId = e.userId ? e.userId.toString() : e.userId
          });
        
          console.log(query);
          // return
          if (this.formData.qualityMonitorId != undefined) {
            monitorEait(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            monitorAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
//
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-top: 20px !important;
}
</style>
